//
//  BPSystemSaleMessagesViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/3/28.
//  Copyright © 2017年 cesh. All rights reserved.
//

#import "BPSystemSaleMessagesViewController.h"
#import "BPMessageTableViewCell.h"
#import "BPCouponViewController.h"
#import "BPComboViewController.h"
#import "UILabel+BPBoundingRect.h"

@interface BPSystemSaleMessagesViewController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray *data;
@property (strong, nonatomic) UITableView *messagesTableView;

@property (strong, nonatomic) NSMutableArray *cellHeights;

@end

@implementation BPSystemSaleMessagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self getMessagesData];
}

- (NSMutableArray *)cellHeights {
    if (_cellHeights == nil) {
        _cellHeights = [NSMutableArray array];
    }
    return _cellHeights;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.alpha = 1.0;
}

- (void)getMessagesData {
    [SVProgressHUD showWithStatus:@"读取中..."];
    NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@%@",requestURL,self.url]
   parameters:@{@"token" : user[@"token"],
                @"page" : @"1",
                @"pageSize" : @"20"}
     progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
             [SVProgressHUD dismiss];
             NSArray *data = responseObject[@"data"];
             self.data = data;
             //没有消息 中央显示暂无消息图标
             if (data.count == 0) {
                 //系统消息
                 if ([self.url isEqualToString:@"?c=Msg&&a=sysMsg"]) {
                     UIImageView *centerImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"m_system_1"]];
                     centerImg.center = CGPointMake(screenW * 0.5, (screenH - 64) * 0.5);
                     [self.view addSubview:centerImg];
                     
                     UILabel *label = [[UILabel alloc] init];
                     label.text = @"暂无消息";
                     label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
                     label.textColor = [UIColor colorWithRed:139/255.0 green:163/255.0 blue:182/255.0 alpha:1/1.0];
                     [label sizeToFit];
                     label.center = CGPointMake(screenW * 0.5, centerImg.bottom + 10 + label.height * 0.5);
                     [self.view addSubview:label];
                 }
                 //促销消息
                 else {
                     UIImageView *centerImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"m_promotion_1"]];
                     centerImg.center = CGPointMake(screenW * 0.5, (screenH - 64) * 0.5);
                     [self.view addSubview:centerImg];
                     
                     UILabel *label = [[UILabel alloc] init];
                     label.text = @"暂无消息";
                     label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
                     label.textColor = [UIColor colorWithRed:139/255.0 green:163/255.0 blue:182/255.0 alpha:1/1.0];
                     [label sizeToFit];
                     label.center = CGPointMake(screenW * 0.5, centerImg.bottom + 10 + label.height * 0.5);
                     [self.view addSubview:label];
                 }
             }
             UITableView *messagesTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenW, screenH - 64)];
             messagesTableView.backgroundColor = [UIColor clearColor];
             messagesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
             self.messagesTableView = messagesTableView;
             messagesTableView.dataSource = self;
             messagesTableView.delegate = self;
             
             [self calculateHeights];
             
             [self.view addSubview:messagesTableView];
         }
         else {
             [SVProgressHUD showInfoWithStatus:@"获取数据失败"];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [SVProgressHUD dismiss];
             });
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [SVProgressHUD showInfoWithStatus:@"请求失败"];
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [SVProgressHUD dismiss];
         });
     }];
}

//根据label的长度和是否可点击计算出cell的高度
- (CGFloat)heightForCommentData:(NSDictionary *)commentData {
    //获取评论文字
    NSString *commentString = commentData[@"content"];
    //取得文字Lbl的高度
    UILabel *comment =[[UILabel alloc]initWithFrame:CGRectMake(10, 50, screenW - 20, 0)];
    comment.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    comment.textColor = [UIColor colorWithRed:141/255.0 green:165/255.0 blue:184/255.0 alpha:1/1.0];
    
    comment.text = commentString;
    
    comment.numberOfLines = 0; //PS：这句很主要，否则默认行数为1，只显示一行文字后面截断了就没有了
    CGRect myRect = [comment boundingRectWithInitSize:comment.frame.size];
    
    CGFloat lblHeight = myRect.size.height;
    
    //判断是否可点击
    long type = [commentData[@"type"] longValue];
    CGFloat detailHeight = 0;
    if (type) {
        detailHeight = 35;
    }
    
    return lblHeight + 95 + detailHeight;
}

- (void)calculateHeights {
    for (NSDictionary *commentData in self.data) {
        [self.cellHeights addObject:@([self heightForCommentData:commentData])];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BPMessageTableViewCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"BPMessageTableViewCell" owner:nil options:nil]lastObject];
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.data = self.data[indexPath.row];
    //评论的label
    UILabel *comment =[[UILabel alloc]initWithFrame:CGRectMake(20, 67, screenW - 40, 0)];
    comment.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    comment.textColor = [UIColor colorWithRed:185/255.0 green:198/255.0 blue:208/255.0 alpha:1/1.0];
    
    comment.text = self.data[indexPath.row][@"content"];
    
    comment.numberOfLines = 0; //PS：这句很主要，否则默认行数为1，只显示一行文字后面截断了就没有了
    CGRect myRect = [comment boundingRectWithInitSize:comment.frame.size];
    comment.frame = CGRectMake(20, 67, screenW - 20, myRect.size.height);
    [cell.contentView addSubview: comment];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellHeight = [self.cellHeights[indexPath.row] floatValue];
    return cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = self.data[indexPath.row];
    //根据type值确定点击调用不同的方法
    NSInteger type = [dict[@"type"] integerValue];
    switch (type) {
            //不可操作
        case 0:
        {
        }
            break;
            //优惠券
        case 1:
        {
            BPCouponViewController *couponVC = [[BPCouponViewController alloc]init];
            [self.navigationController pushViewController:couponVC animated:YES];
        }
            break;
            //套餐
        case 2:
        {
            BPComboViewController *comboVC = [[BPComboViewController alloc]init];
            comboVC.comboID = dict[@"parameter"];
            [self.navigationController pushViewController:comboVC animated:YES];
        }
            break;
            //主页
        case 3:
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
            break;
            //url
        case 4:
        {
            UIViewController *chatVC = [[UIViewController alloc]init];
            chatVC.title = dict[@"title"];
            
            [self.navigationController pushViewController:chatVC animated:YES];
            
            UIWebView *webV = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, screenW, screenH)];
            
            [chatVC.view addSubview:webV];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dict[@"parameter"]]];
            [webV loadRequest:request];
        }
            break;
        default:
            break;
    }
}


@end
